<template>
  <view class="container">
    <!-- 自定义导航栏 -->
    <view class="navbar">
      <view class="navbar-left" @click="goBack">
        <text class="navbar-back">←</text>
      </view>
      <view class="navbar-title">{{ t('drugs_select.title') }}</view>
      <view class="navbar-right">
      </view>
    </view>

    <!-- 选择摘要和操作栏 -->
    <view class="selection-summary-bar">
      <view class="left-actions">
        <view class="action-item" @click="clearAll">
          <text class="action-icon">🗑️</text>
          <text class="action-text">{{ t('drugs_select.clear_list') }}</text>
        </view>
      </view>
      <view class="summary-info">
        <text class="selected-count">{{ t('drugs_select.selected_count', { count: selectedMedicines.length }) }}</text>
        <text class="total-info">{{ totalWeight }}g</text>
      </view>
      <button class="add-complete-btn" @click="addComplete" :disabled="selectedMedicines.length === 0">
        {{ t('drugs_select.complete_selection') }}
      </button>
    </view>

    <!-- 药品输入/显示区域 -->
    <view class="medicine-input-area">
      <view v-if="selectedMedicines.length > 0" class="selected-medicines">
        <view class="selected-medicines-header">
          <text class="selected-medicines-title">{{ selectedMedicines.length > 0 ? t('drugs_select.selected_count', { count: selectedMedicines.length }) : t('drugs_select.no_medicines_selected') }}</text>
        </view>
        <view 
          v-for="(medicine, index) in selectedMedicines" 
          :key="medicine.id" 
          class="medicine-row"
        >
          <view class="medicine-remove" @click="removeMedicine(index)">
            <text class="remove-icon">❌</text>
          </view>
          <view class="medicine-name">{{ medicine.drugs_name }}</view>
                     <view class="medicine-quantity">
             <input 
               v-model="medicine.quantity" 
               :class="['quantity-input', { 'error': medicine.quantityError }]"
               type="number" 
               min="0.1" 
               step="0.1"
               :placeholder="t('medicine.quantity_placeholder')"
               @input="updateTotal"
               @blur="validateQuantity(index)"
             />
             <text class="quantity-unit">{{ medicine.drugs_unit || t('medicine.default_unit') }}</text>
             <text v-if="medicine.quantityError" class="quantity-error">{{ medicine.quantityError }}</text>
           </view>
          <view class="medicine-decoction">
            <picker :range="decoctionOptions" :value="medicine.decoctionIndex" @change="onDecoctionChange($event, index)">
              <view class="decoction-picker">
                <text>{{ getDecoctionText(medicine.decoctionIndex) }}</text>
                <text class="picker-arrow">▼</text>
              </view>
            </picker>
          </view>
        </view>
      </view>
      
      <!-- 搜索输入框 -->
      <view class="search-input-container">
        <input 
          v-model="search" 
          class="search-input" 
          :placeholder="t('drugs_select.search_placeholder')"
          @input="onSearchInput"
          @focus="onSearchFocus"
        />
      </view>
    </view>

    <!-- 中药列表 -->
    <view class="medicine-list" v-if="showMedicineList && search.trim()">
      <view v-if="loading" class="loading">
        {{ t('drugs_select.loading') }}
      </view>
      <view v-else-if="medicineList.length === 0" class="empty-state">
        {{ t('drugs_select.no_more') }}
      </view>
      <view v-else>
        <view 
          v-for="medicine in filteredMedicineList" 
          :key="medicine.id" 
          class="medicine-item"
          @click="selectMedicine(medicine)"
        >
          <view class="medicine-info">
            <view class="medicine-name">{{ medicine.drugs_name }}</view>
            <view class="medicine-details">
              <text class="medicine-form">{{ medicine.drugs_form || t('medicine.no_form') }}</text>
              <text class="medicine-unit">{{ medicine.drugs_unit || t('medicine.default_unit') }}</text>
            </view>
            <view class="medicine-meta">
              <text class="medicine-alias" v-if="medicine.drugs_alias">{{ medicine.drugs_alias }}</text>
              <text class="medicine-pinyin" v-if="medicine.drugs_pinyin">{{ medicine.drugs_pinyin }}</text>
            </view>
          </view>
          <view class="medicine-arrow">></view>
        </view>
      </view>
      
      <!-- 加载更多 -->
      <view v-if="hasMore && !loading" class="load-more">
        <button class="load-more-btn" @click="loadMore">
          {{ t('common.load_more') }}
        </button>
      </view>
    </view>

    <!-- 搜索提示 -->
    <view v-if="!search.trim() && showMedicineList" class="search-tip">
      <text class="tip-text">{{ t('medicine.search_tip') }}</text>
    </view>
  </view>
</template>

<script>
import { getDrugs, getDict } from '@/api/medical.js'
import { useI18n } from 'vue-i18n'

export default {
  data() {
    return {
      search: '',
      page: 1,
      pageSize: 20,
      loading: false,
      hasMore: true,
      medicineList: [],
      searchTimer: null,
      selectedMedicines: [], // 已选择的药品
      showMedicineList: false, // 是否显示药品列表
      decoctionOptions: [], // 煎煮方法选项，从API获取
      historicalMedicines: [], // 历史用药
      totalWeight: 0, // 总重量
    }
  },
  
  setup() {
    const { t } = useI18n()
    return { t }
  },

  computed: {
    filteredMedicineList() {
      if (!this.search) return this.medicineList
      return this.medicineList.filter(medicine => 
        medicine.drugs_name?.toLowerCase().includes(this.search.toLowerCase()) ||
        medicine.drugs_alias?.toLowerCase().includes(this.search.toLowerCase()) ||
        medicine.drugs_pinyin?.toLowerCase().includes(this.search.toLowerCase())
      )
    }
  },

  onLoad(options) {
    this.loadHistoricalMedicines()
    
    // 接收从index页面传递的已选药品数据
    if (options.selected) {
      try {
        const selectedData = JSON.parse(decodeURIComponent(options.selected));
        if (Array.isArray(selectedData)) {
          this.selectedMedicines = selectedData.map(medicine => ({
            ...medicine,
            decoctionIndex: medicine.decoctionIndex || 0,
            quantity: medicine.quantity || ''
          }));
          this.updateTotal();
          // console.log('接收到已选药品:', this.selectedMedicines);
        }
      } catch (error) {
        console.error('解析已选药品数据失败:', error);
      }
    }
  },
  
  async onReady() {
    // 等待煎煮方法选项加载完成后再处理已选药品
    await this.loadDecoctionOptions()
    
    // 如果是从index页面跳转过来的，需要重新处理煎煮方法索引
    if (this.selectedMedicines.length > 0) {
      this.selectedMedicines = this.selectedMedicines.map(medicine => {
        // 确保煎煮方法索引正确
        if (medicine.decoction_method && this.decoctionOptions.length > 0) {
          const index = this.decoctionOptions.findIndex(option => option === medicine.decoction_method)
          return {
            ...medicine,
            decoctionIndex: index >= 0 ? index : 0 // 0 对应 "无"
          }
        }
        return medicine
      })
    }
    
    uni.setNavigationBarTitle({
      title: this.t('medicine.title')
    })
  },

  methods: {
    async loadDecoctionOptions() {
      try {
        const res = await getDict({ code: 'zytsjzff' })
        if (res.code === 200 && res.result) {
          // 按照sort字段排序，确保顺序正确
          this.decoctionOptions = res.result
            .filter(item => item.status === true)
            .sort((a, b) => a.sort - b.sort)
            .map(item => item.label)
        }
      } catch (error) {
        console.error('获取煎煮方法失败:', error)
        // 如果API失败，使用默认值，需要与index.vue中的getDecoctionIndex方法保持一致
        this.decoctionOptions = [
          this.t('drugs_select.decoction_methods.none'),
          this.t('drugs_select.decoction_methods.after'),
          this.t('drugs_select.decoction_methods.before'),
          this.t('drugs_select.decoction_methods.wrap'),
          this.t('drugs_select.decoction_methods.melt'),
          this.t('drugs_select.decoction_methods.take')
        ]
      }
    },

    async initList() {
      // 如果搜索框为空，不进行搜索
      if (!this.search.trim()) {
        this.medicineList = []
        this.hasMore = false
        return
      }
      
      this.page = 1
      this.medicineList = []
      this.hasMore = true
      this.showMedicineList = true
      await this.loadMore()
    },

    async loadMore() {
      if (!this.hasMore || this.loading) return
      
      this.loading = true
      try {
        const res = await getDrugs({
          page: this.page,
          pageSize: this.pageSize,
          name: this.search
        })
        
        if (res.code === 200 && res.result) {
          const newMedicines = res.result.items || []
          const total = res.result.total || 0
          
          if (this.page === 1) {
            this.medicineList = newMedicines
          } else {
            this.medicineList = [...this.medicineList, ...newMedicines]
          }
          
          // 判断是否还有更多数据
          if (newMedicines.length < this.pageSize || this.medicineList.length >= total) {
            this.hasMore = false
          } else {
            this.page++
          }
        } else {
          uni.showToast({
            title: res.message || this.t('common.request_failed'),
            icon: 'none',
            duration: 2000
          })
        }
      } catch (error) {
        console.error('获取中药列表失败:', error)
        uni.showToast({
          title: this.t('common.request_failed'),
          icon: 'none',
          duration: 2000
        })
      } finally {
        this.loading = false
      }
    },

    onSearchInput() {
      // 防抖搜索
      if (this.searchTimer) {
        clearTimeout(this.searchTimer)
      }
      
      // 如果搜索框为空，立即隐藏列表
      if (!this.search.trim()) {
        this.showMedicineList = false
        return
      }
      
      this.searchTimer = setTimeout(() => {
        this.searchMedicines()
      }, 500)
    },

    onSearchFocus() {
      // 只有在有搜索内容时才显示列表
      if (this.search.trim()) {
        this.showMedicineList = true
      }
    },

    searchMedicines() {
      if (this.search.trim()) {
        this.initList()
      }
    },

    selectMedicine(medicine) {
      // 检查是否已经选择过
      const existingIndex = this.selectedMedicines.findIndex(m => m.id === medicine.id)
      if (existingIndex === -1) {
        // 添加新药品
        const newMedicine = {
          ...medicine,
          quantity: '', // 默认数量为空
          decoctionIndex: 0, // 默认煎煮方法
          price: 0.01 // 默认价格，实际应该从API获取
        }
        this.selectedMedicines.push(newMedicine)
        this.updateTotal()
        this.showMedicineList = false
        this.search = ''
        this.medicineList = [] // 清空搜索结果
        
        // 等待DOM更新后，聚焦到新添加的药品数量输入框
        this.$nextTick(() => {
          const quantityInputs = document.querySelectorAll('.quantity-input')
          if (quantityInputs.length > 0) {
            const lastInput = quantityInputs[quantityInputs.length - 1]
            lastInput.focus()
          }
        })
      } else {
        uni.showToast({
          title: this.t('order.medicine_already_selected'),
          icon: 'none',
          duration: 2000
        })
      }
    },

    removeMedicine(index) {
      this.selectedMedicines.splice(index, 1)
      this.updateTotal()
    },

    clearAll() {
      if (this.selectedMedicines.length > 0) {
        uni.showModal({
          title: this.t('drugs_select.confirm_clear_title'),
          content: this.t('drugs_select.confirm_clear'),
          success: (res) => {
            if (res.confirm) {
              this.selectedMedicines = []
              this.updateTotal()
            }
          }
        })
      }
    },

    toggleSingleRow() {
      // 切换单排显示模式
      uni.showToast({
        title: '单排模式',
        icon: 'none',
        duration: 1000
      })
    },

    onDecoctionChange(e, index) {
      this.selectedMedicines[index].decoctionIndex = e.detail.value
      // 同步更新煎煮方法文本
      this.selectedMedicines[index].decoction_method = this.decoctionOptions[e.detail.value]
      // console.log('煎煮方法已更新:', this.selectedMedicines[index].decoction_method)
    },
    
    getDecoctionText(index) {
      // 安全获取煎煮方法文本，防止在decoctionOptions未加载时出错
      if (this.decoctionOptions.length > 0 && index >= 0 && index < this.decoctionOptions.length) {
        return this.decoctionOptions[index]
      }
      // 如果decoctionOptions未加载，使用默认值
      const defaultOptions = [
        this.t('drugs_select.decoction_methods.none'),
        this.t('drugs_select.decoction_methods.after'),
        this.t('drugs_select.decoction_methods.before'),
        this.t('drugs_select.decoction_methods.wrap'),
        this.t('drugs_select.decoction_methods.melt'),
        this.t('drugs_select.decoction_methods.take')
      ]
      return defaultOptions[index] || this.t('drugs_select.decoction_methods.none')
    },

    validateQuantity(index) {
      const medicine = this.selectedMedicines[index]
      if (!medicine.quantity || medicine.quantity.trim() === '') {
        medicine.quantityError = this.t('drugs_select.quantity_required')
      } else if (parseFloat(medicine.quantity) < 0.1) {
        medicine.quantityError = this.t('drugs_select.quantity_min_error')
      } else {
        medicine.quantityError = ''
      }
      this.updateTotal()
    },

    updateTotal() {
      // 计算总重量和总价格
      this.totalWeight = this.selectedMedicines.reduce((sum, medicine) => {
        return sum + (parseFloat(medicine.quantity) || 0)
      }, 0).toFixed(1)
      
      // this.totalPrice = this.selectedMedicines.reduce((sum, medicine) => {
      //   return sum + ((parseFloat(medicine.quantity) || 0) * (parseFloat(medicine.price) || 0.01))
      // }, 0).toFixed(3)
    },

    addComplete() {
      if (this.selectedMedicines.length === 0) {
        uni.showToast({
          title: this.t('drugs_select.no_medicines_selected'),
          icon: 'none',
          duration: 2000
        })
        return
      }

      // 验证所有药品数量是否已填写
      const invalidMedicines = this.selectedMedicines.filter(medicine => 
        !medicine.quantity || medicine.quantity.trim() === '' || parseFloat(medicine.quantity) < 0.1
      )
      
      if (invalidMedicines.length > 0) {
        uni.showToast({
          title: this.t('drugs_select.all_quantities_required'),
          icon: 'none',
          duration: 2000
        })
        return
      }

      // 处理返回数据，确保包含煎煮方法
      const processedMedicines = this.selectedMedicines.map(medicine => ({
        ...medicine,
        decoction_method: this.decoctionOptions[medicine.decoctionIndex] || this.t('drugs_select.decoction_methods.none')
      }));

      // 发送选中的中药数据
      const eventChannel = this.getOpenerEventChannel()
      eventChannel.emit('medicineSelected', processedMedicines)
      uni.navigateBack()
    },

    loadHistoricalMedicines() {
      // 模拟历史用药数据，实际应该从本地存储或API获取
      this.historicalMedicines = [
        { id: 1, drugs_name: this.t('drugs_select.historical_medicines.sharen'), drugs_unit: this.t('drugs_select.units.gram') },
        { id: 2, drugs_name: this.t('drugs_select.historical_medicines.dangshen'), drugs_unit: this.t('drugs_select.units.gram') },
        { id: 3, drugs_name: this.t('drugs_select.historical_medicines.danggui'), drugs_unit: this.t('drugs_select.units.gram') }
      ]
    },

    addHistoricalMedicine(medicine) {
      // 添加历史用药
      const existingIndex = this.selectedMedicines.findIndex(m => m.id === medicine.id)
      if (existingIndex === -1) {
        const newMedicine = {
          ...medicine,
          quantity: '', // 默认数量为空
          decoctionIndex: 0, // 0 对应 "无"
          price: 0.01
        }
        this.selectedMedicines.push(newMedicine)
        this.updateTotal()
        
        // 等待DOM更新后，聚焦到新添加的药品数量输入框
        this.$nextTick(() => {
          const quantityInputs = document.querySelectorAll('.quantity-input')
          if (quantityInputs.length > 0) {
            const lastInput = quantityInputs[quantityInputs.length - 1]
            lastInput.focus()
          }
        })
      } else {
        uni.showToast({
          title: this.t('order.medicine_already_selected'),
          icon: 'none',
          duration: 2000
        })
      }
    },

    quickPrescription() {
      // 快速录方功能
      uni.showToast({
        title: this.t('drugs_select.quick_prescription'),
        icon: 'none',
        duration: 1000
      })
    },

    dedicatedKeyboard() {
      // 专用键盘功能
      uni.showToast({
        title: this.t('drugs_select.dedicated_keyboard'),
        icon: 'none',
        duration: 1000
      })
    },

    goBack() {
      if (this.selectedMedicines.length > 0) {
        uni.showModal({
          title: this.t('drugs_select.confirm_leave_title'),
          content: this.t('drugs_select.confirm_leave'),
          success: (res) => {
            if (res.confirm) {
              uni.navigateBack()
            }
          }
        })
      } else {
        uni.navigateBack()
      }
    }
  }
}
</script>

<style scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
}

.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #e9ecef;
  position: sticky;
  top: 0;
  z-index: 100;
}

.navbar-left {
  width: 60rpx;
}

.navbar-back {
  font-size: 36rpx;
  color: #333;
}

.navbar-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.navbar-right {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.navbar-dots {
  font-size: 32rpx;
  color: #666;
}

.navbar-target {
  font-size: 28rpx;
}

 .selection-summary-bar {
   display: flex;
   align-items: center;
   justify-content: space-between;
   padding: 24rpx 30rpx;
   background-color: #fff;
   border-bottom: 1rpx solid #e9ecef;
   margin-bottom: 16rpx;
 }

 .left-actions {
   display: flex;
   gap: 30rpx;
   margin-right: 40rpx;
 }

 .action-item {
   display: flex;
   align-items: center;
   gap: 8rpx;
   cursor: pointer;
   padding: 8rpx 16rpx;
   border-radius: 20rpx;
   background-color: #f8f9fa;
   border: 1rpx solid #e9ecef;
   transition: all 0.2s;
 }
 
 .action-item:active {
   background-color: #e9ecef;
   transform: scale(0.98);
 }

.action-icon {
  font-size: 24rpx;
}

.action-text {
  font-size: 24rpx;
  color: #666;
}

 .summary-info {
   display: flex;
   flex-direction: column;
   align-items: center;
   gap: 8rpx;
   padding: 16rpx 24rpx;
   background-color: #f8f9fa;
   border-radius: 20rpx;
   border: 1rpx solid #e9ecef;
   min-width: 100rpx;
 }

.selected-count {
  font-size: 26rpx;
  color: #333;
  font-weight: 600;
}

.total-info {
  font-size: 22rpx;
  color: #666;
}

 .add-complete-btn {
   background-color: #007aff;
   color: #fff;
   border: none;
   border-radius: 40rpx;
   padding: 16rpx 32rpx;
   font-size: 28rpx;
   font-weight: 500;
   margin-left: 40rpx;
 }

.add-complete-btn:disabled {
  background-color: #ccc;
  color: #999;
}

 .medicine-input-area {
   background-color: #fff;
   padding: 24rpx 30rpx;
   border-bottom: 1rpx solid #e9ecef;
   margin-top: 8rpx;
 }

 .selected-medicines {
   margin-bottom: 20rpx;
 }
 
 .selected-medicines-header {
   padding: 16rpx 0;
   border-bottom: 1rpx solid #e9ecef;
   margin-bottom: 16rpx;
 }
 
 .selected-medicines-title {
   font-size: 28rpx;
   font-weight: 600;
   color: #333;
   display: block;
 }

 .medicine-row {
   display: flex;
   align-items: center;
   gap: 20rpx;
   padding: 24rpx 0;
   border-bottom: 1rpx solid #f0f0f0;
   margin-bottom: 8rpx;
 }

.medicine-row:last-child {
  border-bottom: none;
}

.medicine-remove {
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.remove-icon {
  font-size: 24rpx;
  color: #ff4d4f;
}

.medicine-name {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.medicine-quantity {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

 .quantity-input {
   width: 80rpx;
   height: 60rpx;
   border: 1rpx solid #ddd;
   border-radius: 8rpx;
   text-align: center;
   font-size: 26rpx;
   padding: 0 8rpx;
 }
 
 .quantity-input:focus {
   border-color: #007aff;
   outline: none;
 }
 
 .quantity-input.error {
   border-color: #ff4d4f;
 }

 .quantity-unit {
   font-size: 24rpx;
   color: #666;
 }
 
 .quantity-error {
   font-size: 20rpx;
   color: #ff4d4f;
   margin-top: 4rpx;
   display: block;
   white-space: nowrap;
 }

.medicine-decoction {
  min-width: 120rpx;
}

.decoction-picker {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12rpx 16rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  background-color: #f8f9fa;
  font-size: 24rpx;
  color: #333;
}

.picker-arrow {
  font-size: 20rpx;
  color: #999;
}

 .search-input-container {
   margin-top: 24rpx;
   padding-top: 16rpx;
   border-top: 1rpx solid #f0f0f0;
 }

.search-input {
  width: 100%;
  height: 80rpx;
  padding: 0 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 40rpx;
  font-size: 28rpx;
  background-color: #f8f9fa;
}

.medicine-list {
  background-color: #fff;
  margin-top: 20rpx;
}

.loading, .empty-state {
  text-align: center;
  padding: 60rpx 0;
  color: #666;
  font-size: 28rpx;
}

.medicine-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  margin-bottom: 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.medicine-info {
  flex: 1;
}

.medicine-name {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 16rpx;
  line-height: 1.4;
}

.medicine-details {
  display: flex;
  gap: 20rpx;
  margin-bottom: 12rpx;
}

.medicine-form, .medicine-unit {
  font-size: 24rpx;
  color: #666;
  background-color: #f0f0f0;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
}

.medicine-meta {
  display: flex;
  gap: 16rpx;
}

.medicine-alias, .medicine-pinyin {
  font-size: 22rpx;
  color: #999;
}

.medicine-arrow {
  font-size: 32rpx;
  color: #ccc;
  margin-left: 20rpx;
}

.load-more {
  text-align: center;
  padding: 40rpx 0;
}

.load-more-btn {
  background-color: #f8f9fa;
  color: #666;
  border: 1rpx solid #ddd;
  border-radius: 40rpx;
  padding: 20rpx 40rpx;
  font-size: 28rpx;
}

.bottom-action-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  border-top: 1rpx solid #e9ecef;
  padding: 20rpx 30rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.left-section {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.historical-text {
  font-size: 24rpx;
  color: #666;
  white-space: nowrap;
}

.historical-pills {
  display: flex;
  gap: 16rpx;
}

.historical-pill {
  background-color: #f0f0f0;
  color: #333;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 22rpx;
  cursor: pointer;
}

.right-actions {
  display: flex;
  gap: 16rpx;
}

.quick-action-btn {
  display: flex;
  align-items: center;
  gap: 8rpx;
  background-color: #f8f9fa;
  color: #666;
  border: 1rpx solid #ddd;
  border-radius: 20rpx;
  padding: 12rpx 20rpx;
  font-size: 22rpx;
}

.action-icon {
  font-size: 20rpx;
}

.search-tip {
  text-align: center;
  padding: 40rpx 0;
  color: #999;
  font-size: 28rpx;
}

.tip-text {
  display: inline-block;
  padding: 10rpx 20rpx;
  background-color: #f0f0f0;
  border-radius: 20rpx;
}
</style>
